<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app\index\service;

use app\index\model\Advert;
use app\index\model\Commodity;
use app\index\model\RecommendGoods;
use app\index\model\Renovation;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\HttpException;
use think\facade\Cache;
use think\facade\Db;

class RenovationService
{
    private $mid;

    public function __construct()
    {
        global $mid;
        $this->mid = $mid;
    }

    public function getRenovationInfo(array $data)
    {
        //1-商城首页 2-商品详情 3-会员中心
        if (isset($data['is_preview']) && $data['is_preview'] == 1) {
            $res = Renovation::find($data['id']);
        } else {
            $res = Renovation::where('page_type', $data['type'])
                ->where('status', 2)
                ->where('mall_id', $this->mid)
                ->whereRaw("FIND_IN_SET('" . $data['user_type'] . "',source)")
                ->find();
        }

        if (empty($res)) throw new HttpException(HTTP_INVALID, "页面不存在");
        return [HTTP_SUCCESS, $res['configure']];
    }

    public function custom(int $id)
    {
        $find = Renovation::find($id);
        if (empty($find)) throw new HttpException(HTTP_INVALID, "页面不存在");
        return [HTTP_SUCCESS, $find['configure']];
    }

    public function advert()
    {
        global $mid;
        $find = Advert::where('mall_id', $mid)->find();
        if (!isset($find)) $find['content'] = null;
        return [HTTP_SUCCESS, $find['content']];
    }

    public function getRecommendGoods(array $data)
    {
        $res = RecommendGoods::where('mall_id', $this->mid)->find();
        if (!empty($res)) $res = $res->toArray();
        $goods = json_decode(json_encode($res['content']), true)['goods'];
        $commditys = Commodity::where('id', 'IN', $goods)
            ->field('type,name as goods_name,subtitle,master,classify_id,id,has_sku,total,is_original_price,original_price,
                           sell_price,min_price,max_price,sort,is_virtual,sell,virtual_sell')
            ->paginate(['page' => $data['page'],'list_rows' => $data['size']]);
        $list = $commditys->toArray();
        return [HTTP_SUCCESS, $list];
    }

    public function getRecommendConfig()
    {
        $res = RecommendGoods::where('mall_id', $this->mid)->find();
        return [HTTP_SUCCESS, $res];
    }
}